//package com.panda.web.controller.aims;
//
//import com.itextpdf.io.image.ImageData;
//import com.itextpdf.io.image.ImageDataFactory;
//import com.itextpdf.kernel.events.PdfDocumentEvent;
//import com.itextpdf.kernel.pdf.PdfDocument;
//import com.itextpdf.text.*;
//import com.itextpdf.text.pdf.BaseFont;
//import com.itextpdf.text.pdf.PdfContentByte;
//import com.itextpdf.text.pdf.PdfPageEventHelper;
//import com.itextpdf.text.pdf.PdfWriter;
//import com.panda.web.controller.commons.KouZiController;
//import com.panda.web.entity.aims.AgentCallbackRequest;
//import com.panda.web.entity.aims.CallRecords;
//import com.panda.web.mapper.aims.CallRecordsMapper;
//import lombok.extern.slf4j.Slf4j;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.web.bind.annotation.GetMapping;
//import org.springframework.web.bind.annotation.RequestMapping;
//import org.springframework.web.bind.annotation.RestController;
//
//import java.io.File;
//import java.io.FileOutputStream;
//import java.io.IOException;
//import java.util.Comparator;
//import java.util.List;
//import java.util.stream.Collectors;
//@Slf4j
//@RestController
//@RequestMapping("/pdf")
//public class TextPdf {
//
//    private static Font titleFont;
//    private static Font agentFont;
//    private static Font userFont;
////    private static final String BACKGROUND_PATH = "/www/wwwroot/comments/picture/50.png"; // 背景图片路径
//    private static final String BACKGROUND_PATH = "C:/Users/Administrator/Desktop/AI面试/jilu/50.png"; // 背景图片路径
//    static {
//        try {
//            // 使用更可靠的中文字体加载方式
//            String fontPath = "C:/Users/Administrator/Desktop/AI面试/jilu/msyh.ttf"; // 使用系统自带的黑体
////            String fontPath = "/www/wwwroot/comments/Fonts/msyh.ttf"; // 使用系统自带的黑体
//            BaseFont bfChinese = BaseFont.createFont(fontPath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
//
//            titleFont = new Font(bfChinese, 16, Font.BOLD);
////            agentFont = new Font(bfChinese, 12, Font.BOLD, new BaseColor(25, 91, 169));
////            userFont = new Font(bfChinese, 12, Font.NORMAL, BaseColor.BLACK);
//            agentFont = new Font(bfChinese, 12, Font.NORMAL,  BaseColor.BLACK);
//            userFont = new Font(bfChinese, 12, Font.BOLD,new BaseColor(25, 91, 169));
//        } catch (Exception e) {
//            // 回退到默认字体
//            titleFont = new Font(Font.FontFamily.HELVETICA, 16, Font.BOLD);
//            agentFont = new Font(Font.FontFamily.HELVETICA, 12, Font.BOLD, new BaseColor(25, 91, 169));
//            userFont = new Font(Font.FontFamily.HELVETICA, 12, Font.NORMAL, BaseColor.BLACK);
//            e.printStackTrace();
//        }
//    }
////    static {
////        try {
////            // 使用itext-asian支持中文字体
////            BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
////            titleFont = new Font(bfChinese, 16, Font.BOLD);
////            agentFont = new Font(bfChinese, 12, Font.BOLD, BaseColor.BLUE);
////            userFont = new Font(bfChinese, 12, Font.NORMAL, BaseColor.BLACK);
////        } catch (Exception e) {
////            // 回退到默认字体
////            titleFont = new Font(Font.FontFamily.HELVETICA, 16, Font.BOLD);
////            agentFont = new Font(Font.FontFamily.HELVETICA, 12, Font.BOLD, BaseColor.BLUE);
////            userFont = new Font(Font.FontFamily.HELVETICA, 12, Font.NORMAL, BaseColor.BLACK);
////        }
////    }
//    @Autowired
//    CallRecordsMapper callRecordsMapper;
//
//    @GetMapping("/aaa")
//    private void printAgentStop(AgentCallbackRequest request) {
//        // 获取通话记录
//        List<CallRecords> callRecords = callRecordsMapper.findByInstanceId(request.getInstanceId());
//
//        try {
//            // 生成PDF报告
//            String outputPath = "C:/Users/Administrator/Desktop/AI面试/jilu/" + request.getInstanceId() + ".pdf";
//            generateSimplePdf(callRecords, outputPath);
//
//            System.out.println("PDF报告生成成功: " + outputPath);
//        } catch (Exception e) {
//            System.err.println("生成PDF报告失败: " + e.getMessage());
//            e.printStackTrace();
//        }
//    }
//
//    private void generateSimplePdf(List<CallRecords> callRecords, String outputPath)
//            throws DocumentException, java.io.IOException {
//        File file = new File(outputPath);
//        file.getParentFile().mkdirs();
//
//        List<CallRecords> sortedRecords = callRecords.stream()
//                .sorted(Comparator.comparing(CallRecords::getCreateTime))
//                .collect(Collectors.toList());
//
//        // 使用A4页面尺寸，增加边距
//        Document document = new Document(PageSize.A4, 40, 40, 60, 40);
//        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
//
//        // 添加背景处理器
//        writer.setPageEvent(new BackgroundEvent(BACKGROUND_PATH));
//        document.open();
//
//        // 添加标题（带底部间距）
//        Paragraph title = new Paragraph("AI面试记录", titleFont);
//        title.setAlignment(Element.ALIGN_CENTER);
//        title.setSpacingAfter(25f);
//        document.add(title);
//
//        // 标志变量
//        boolean foundFirstQuestion = false;
//        boolean isNewQuestion = false;
//        String currentQuestion = "";
//        boolean isFirstQuestion = false;
//
//        // 添加对话内容
//        for (CallRecords record : sortedRecords) {
//            String text = record.getText();
//            text = text.replace("面试到此结束，感谢您的参与", "");
//
//            // 检查是否是新题目开始
//            boolean isQuestionLine = text.contains("第") && text.contains("题") && "agent".equals(record.getRole());
//            boolean isMSZJ = text.contains("面试总结") && "agent".equals(record.getRole());
//
//            // 如果还未找到第一题
//            if (!foundFirstQuestion) {
//                if (isQuestionLine && text.contains("第一题")) {
//                    foundFirstQuestion = true;
//                    isFirstQuestion = true;
//                    int startIndex = text.indexOf("第一题");
//                    if (startIndex >= 0) {
//                        text = text.substring(startIndex);
//                    }
//                } else {
//                    continue;
//                }
//            }
//
//            // 处理题目行和面试总结行的换行符
//            if (isQuestionLine) {
//                text = text.replaceAll("(第\\s*[二三四五六七八九十]+\\s*题\\s*)", "\n\n$1");
//                // 如果是新题目，增加额外间距
//                if (!text.equals(currentQuestion)) {
//                    currentQuestion = text;
//                    isNewQuestion = true;
//                    isFirstQuestion = text.contains("第一题");
//                }
//            } else if (isMSZJ) {
//                text = text.replaceAll("(\\s*面试总结\\s*)", "\n\n$1");
//                // 面试总结前增加额外间距
//                isNewQuestion = true;
//            }
//
//            Font font = "agent".equals(record.getRole()) ? agentFont : userFont;
//            String prefix = "agent".equals(record.getRole()) ? (isFirstQuestion ? "" : "面试官: ") : "用户: ";
//
//            if (isNewQuestion) {
//                isNewQuestion = false;
//                isFirstQuestion = false;
//            }
//
//            Paragraph paragraph = new Paragraph(prefix + text, font);
//            document.add(paragraph);
//        }
//
//        document.close();
//    }
//
////二版
////    private void generateSimplePdf(List<CallRecords> callRecords, String outputPath)
////            throws DocumentException, java.io.IOException {
////        File file = new File(outputPath);
////        file.getParentFile().mkdirs();
////
////        List<CallRecords> sortedRecords = callRecords.stream()
////                .sorted(Comparator.comparing(CallRecords::getCreateTime))
////                .collect(Collectors.toList());
////
////        // 使用A4页面尺寸，增加边距
////        Document document = new Document(PageSize.A4, 40, 40, 60, 40);
////        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
////
////        // 添加背景处理器
////        writer.setPageEvent(new BackgroundEvent(BACKGROUND_PATH));
////
////        document.open();
////
////        // 添加标题（带底部间距）
////        Paragraph title = new Paragraph("AI智能面试通话记录", titleFont);
////        title.setAlignment(Element.ALIGN_CENTER);
////        title.setSpacingAfter(25f);
////        document.add(title);
////
////        // 添加对话内容（带左侧缩进）
////        for (CallRecords record : sortedRecords) {
////            Font font = "agent".equals(record.getRole()) ? agentFont : userFont;
////            String prefix = "agent".equals(record.getRole()) ? "面试官:": "用户:";
////
////            Paragraph paragraph = new Paragraph(prefix + record.getText(), font);
////            paragraph.setAlignment(Element.ALIGN_LEFT);
////            paragraph.setIndentationLeft(20);
////            paragraph.setSpacingAfter(8f);
////            document.add(paragraph);
////        }
////
////        document.close();
////    }
//
//    // 修正背景图片铺满问题   ,添加背景图片
//    public static class BackgroundEvent extends PdfPageEventHelper {
//        private final String backgroundImage;
//
//        public BackgroundEvent(String backgroundImage) {
//            this.backgroundImage = backgroundImage;
//        }
//
//        @Override
//        public void onEndPage(PdfWriter writer, Document document) {
//            try {
//                PdfContentByte canvas = writer.getDirectContentUnder();
//                Image img = Image.getInstance(backgroundImage);
//
//                // 确保图片铺满整个页面 - 关键修改
//                img.scaleAbsolute(document.getPageSize().getWidth(), document.getPageSize().getHeight());
//                img.setAbsolutePosition(0, 0);
//
//                canvas.addImage(img);
//            } catch (Exception e) {
//                System.err.println("无法添加背景图片: " + e.getMessage());
//            }
//        }
//    }
//
////一版
////    private void generateSimplePdf(List<CallRecords> callRecords, String outputPath)
////            throws DocumentException, java.io.IOException {
////        // 确保目录存在
////        File file = new File(outputPath);
////        file.getParentFile().mkdirs();
////
////        // 按创建时间排序
////        List<CallRecords> sortedRecords = callRecords.stream()
////                .sorted(Comparator.comparing(CallRecords::getCreateTime))
////                .collect(Collectors.toList());
////        // 初始化PDF文档
////        Document document = new Document();
////        PdfWriter.getInstance(document, new FileOutputStream(file));
////        document.open();
////
////        // 添加标题（居中）
////        Paragraph title = new Paragraph("AI智能面试通话记录", titleFont);
////        title.setAlignment(Element.ALIGN_CENTER);
////        title.setSpacingAfter(20f);
////        document.add(title);
////
////        // 添加对话内容
////        for (CallRecords record : sortedRecords) {
////            Font font = "agent".equals(record.getRole()) ? agentFont : userFont;
////            String prefix = "agent".equals(record.getRole()) ? "面试官:  " : "用户:  ";
////
////            Paragraph paragraph = new Paragraph(prefix + record.getText(), font);
////            paragraph.setSpacingAfter(10f);
////            document.add(paragraph);
////        }
////
////        document.close();
////    }
//}